package be.sc.classicnetwork.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Lob;
import javax.swing.ImageIcon;

import be.sc.classicnetwork.util.PropertiesUtils;
import be.sc.classicnetwork.util.Utils;

/**
 * Entity for Image.
 */
@Entity
public class Image extends AbstractEntity {

    private static final long serialVersionUID = 9061338716522225817L;

    @Lob
    @Column(length = 518576)
    private byte[] file;

    @Lob
    private byte[] thumb;

    /**
     * Constructor.
     */
    public Image() {
	super();
    }

    /**
     * Constructor.
     */
    public Image(String id) {
	super(id);
    }

    /**
     * Constructor.
     */
    public Image(byte[] file) {
	super();
	setFile(file);
    }

    /**
     * isImageGreaterThanMaxWidth.
     */
    private boolean isImageGreaterThanMaxWidth(byte[] image) {
	java.awt.Image inImage = new ImageIcon(image).getImage();
	int maxWidth = Integer.parseInt(PropertiesUtils.IMAGE_MAX_WIDTH);
	return (inImage.getWidth(null) > maxWidth);
    }

    /**
     * isEmpty.
     */
    public boolean isEmpty() {
	return (this.file == null || this.file.length == 0);
    }

    public byte[] getFile() {
	return file;
    }

    /**
     * Scales the file to IMAGE_MAX_WIDTH if the original width is greater than
     * IMAGE_MAX_WIDTH and generates the thumb image.
     */
    public void setFile(byte[] file) {
	// check the file
	if (file == null || file.length == 0) {
	    this.file = null;
	    this.thumb = null;
	    return;
	}

	// if width bigger than IMAGE_MAX_WIDTH then scale
	if (isImageGreaterThanMaxWidth(file)) {
	    log.debug("Image width bigger than max width, scaling down...");
	    this.file = Utils.scaleImage(file, Integer.parseInt(PropertiesUtils.IMAGE_MAX_WIDTH));
	} else {
	    this.file = file;
	}

	// generate the thumb
	this.thumb = Utils.scaleImage(file, Integer.parseInt(PropertiesUtils.IMAGE_THUMB_WIDTH));
    }

    public byte[] getThumb() {
	return thumb;
    }

    public void setThumb(byte[] thumb) {
	this.thumb = thumb;
    }

}
